package controller

import (
	"errors"
	"ginfast/api/middleware"
	"ginfast/api/system/dto"
	"ginfast/api/system/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Role 系统角色
type Role struct {
}

// ListHandler 列表
func (Role) ListHandler(c *gin.Context) {
	var p dto.Where
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	t := middleware.GetUser(c)
	if t.UserName != model.UserName {
		p.CreatedBy = t.UserName
	}
	var data []model.Role
	total, _ := p.DbModelWhere(&model.Role{}).Find(&data)
	ctx.WriteTotal(total, data)
}

// GetHandler 查询
func (Role) GetHandler(c *gin.Context) {
	ctx, id := ginx.JSON(c).ParamUInt("id")
	var role model.Role
	err := orm.DbFirstByID(&role, id)
	ctx.WriteData(role.RoleOpt, err)
}

func (Role) AllocatedListPageHandler(c *gin.Context) {
	var p dto.Where
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	var data []model.User
	total, _ := p.DbModelWhere(&model.User{}, func(dw *orm.DbWhere) {
		dw.Add("RoleID = ?", p.RoleID)
	}).Find(&data)
	ctx.WriteTotal(total, data)
}

// 获取当前登录用户创建的用户并且角色不为roleId
func (Role) UnAllocatedListPageHandler(c *gin.Context) {
	var p dto.Where
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	p.CreatedBy = middleware.GetUser(c).UserName
	var data []model.User
	total, _ := p.DbModelWhere(&model.User{}, func(dw *orm.DbWhere) {
		dw.Add("RoleID != ?", p.RoleID)
	}).Find(&data)
	ctx.WriteTotal(total, data)
}

// AddHandler 新增
func (Role) AddHandler(c *gin.Context) {
	var p model.Role
	//获取参数
	ctx, err := ginx.MustBind(c, &p.RoleOpt)
	if err != nil {
		return
	}
	if err := orm.DbFirstBy(&p, "Name = ? || Key = ?", p.Name, p.Key); err == nil {
		ctx.WriteError(errors.New("role record exist"))
		return
	}
	p.CreatedBy = middleware.GetUser(c).UserName
	p.DataScope = "1"
	err = orm.DbCreate(&p)
	ctx.WriteError(err)
}

// UpdateHandler 修改
func (Role) UpdateHandler(c *gin.Context) {
	var p model.Role
	ctx, err := ginx.MustBind(c, &p.RoleOpt)
	if err != nil {
		return
	}
	p.UpdatedBy = middleware.GetUser(c).UserName
	// 更新数据
	err = orm.DbUpdateModelByID(&p, p.ID)
	ctx.WriteError(err)
}

// ChangeStatusHandler 改变角色状态
func (Role) ChangeStatusHandler(c *gin.Context) {
	var p model.Role
	//获取参数
	ctx, err := ginx.MustBind(c, &p.RoleOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateFields(&p, "Status")
	ctx.WriteError(err)
}

type roleSelectAuth struct {
	UserIds string `form:"userIds"` // 菜单状态
	RoleId  uint64 `form:"roleId"`  // 菜单状态
}

// AuthSelectAllHandler 修改
func (Role) AuthSelectAllHandler(c *gin.Context) {
	var p roleSelectAuth
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	userIds := util.StringSplit(p.UserIds, ",")
	err = orm.DbUpdateByID(&model.User{}, userIds, orm.H{"RoleID": p.RoleId})
	ctx.WriteError(err)
}

type roleCancelAuth struct {
	UserId uint64 `form:"userId"` // 菜单状态
	RoleId string `form:"roleId"` // 菜单状态
}

// AuthCancelHandler
func (Role) AuthCancelHandler(c *gin.Context) {
	var p roleCancelAuth
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	err = orm.DbUpdateByID(&model.User{}, p.UserId, orm.H{"RoleID": 0})
	ctx.WriteError(err)
}

// DeleteHandler 删除角色
func (Role) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Role{}, ginx.JSON(c))
}

func (o Role) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/authUser/allocatedList", o.AllocatedListPageHandler)
	r.GET("/authUser/unallocatedList", o.UnAllocatedListPageHandler)
	r.POST("", o.AddHandler)
	r.PUT("/changeStatus", o.ChangeStatusHandler)
	r.PUT("", o.UpdateHandler)
	r.PUT("/authUser/selectAll", o.AuthSelectAllHandler)
	r.PUT("/authUser/cancel", o.AuthCancelHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
